//定制请求的实例
import { ElMessage } from 'element-plus'
import axios from "axios";
import { useTokenStore } from '@/stores/token.js'
import  router  from '@/router/index.js'
// const url="http://localhost:8080";
const url="/api";
const service= axios.create({
    baseURL:url,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" }
});
// const router = useRouter();
service.interceptors.request.use(
    (config)=>{
        const tokenStore=useTokenStore();
        if (tokenStore.token){
            config.headers.Authorization=tokenStore.token;
        }
        return config;
    },
    ()=>{

    }
)

service.interceptors.response.use(
    result=>{
        if (result.data.code===200){
            return result.data;
        }
        // alert(result.data.message || '服务异常');
        ElMessage.error( result.data.message ||'服务异常')
        return Promise.reject(result.data);
    },
    error => {
        if(error.response.status===401){
            const tokenStore=useTokenStore();
            ElMessage.error('请先登录！')
            tokenStore.removeToken();
            router.push('/login')
        }else{
            ElMessage.error('服务异常');
        }
        return Promise.reject(error);//异步的状态转化成失败的状态
    }
)

export default service ;